<template>
<div class="reply">
<van-form @submit="handleSubmit">
  <van-field v-model="askTitle" required
  v-if="!isExpert"
	name="askTitle" label="标题" placeholder="请输入标题"	:rules="[{ required: true, trigger: 'change' }]"/>
	<!-- -->
  <van-field
	v-model="desc"
	rows="6"
	autosize
	:label="isExpert ? '回答' : '详细描述'"
	type="textarea"
	show-word-limit
	:placeholder="isExpert ? '请输入详细回答' : '请输入详细描述'"
	maxlength="500"
	required
	name="desc"
	:rules="[{ required: true}]"
  />
  <!--  -->
  <van-field name="uploader" label="上传图片">
	<template #input>
		<van-uploader multiple max-count="9" :max-size="5 * 1024 * 1024"  v-model="FileList" :upload-icon="require('@/assets/icon/upload-icon.png')" />
	</template>
	</van-field>
  <div class="button-bottom pd1">
	<van-button block type="info" native-type="submit">提交</van-button>
  </div>
</van-form>
	</div>
</template>
<script>
import { Form, Field, Button, Uploader } from 'vant'
import API from '@/services'
export default {
	data() {
		return {
			askTitle: '',
			desc: '',
			FileList: [],
		}
	},
	props: ['role', 'id'],
	components: { VanForm: Form, VanField: Field, VanButton: Button, VanUploader: Uploader },
	methods: {
		async handleSubmit() {
			let params = null
			let currentRequest = null
			let linkName = ''
			if (this.isExpert) {
				params = {
					content: this.desc,
					problemId: this.id,
				}
				currentRequest = API.writeReply
				linkName = 'OnlineReply'
			} else {
				params = {
					description: this.desc,
					title: this.askTitle,
				}
				currentRequest = API.askProblems
				linkName = 'OnlineAsk'
			}
			const uploadRequestList = this.FileList.map(item => {
				const Form = new FormData()
				Form.append('file', item.file)
				Form.append('type', 1)
				return API.uploadimg({ data: Form })
			})

			try {
				const resList = await Promise.all(uploadRequestList)
				const imgs = resList.map(item => item.url).join(',')
				params.imgs = imgs
				await currentRequest({ data: params })
				this.$toast({
					type: 'success',
					message: '提交成功',
				})
				this.$router.replace({
					name: linkName,
				})
			} catch (error) {
				this.$toast({
					type: 'fail',
					message: error.message,
				})
			}
		},
	},
	computed: {
		isExpert() {
			return this.role === 'expert'
		},
	},
}
</script>
<style lang="scss" scoped>
.reply {
	padding-bottom: 100px;
}
.pd1{
	background-color: #F9F9F9;
}
</style>
